<template>
  <div class="panel-tab__content">
    <el-form size="mini" label-width="90px" @submit.native.prevent>
      <el-form-item label="会签类型">
        <template slot="label">
          <el-tooltip effect="dark" placement="top">
            <i class="el-icon-question"/>
            <template slot="content">
              非会签（也可理解为或签）：单人或多人审批时，一名审批人【审批】，流程即往下流转<br/>
              会签：多人审批时，同时可进行审批，满足配置的完成策略（完成条件），流程即往下流转<br/>
              串签：多人审批时，按顺序依次审批，满足配置的完成策略（完成条件），流程即往下流转<br/>
            </template>
          </el-tooltip>
          <span> 会签类型</span>
        </template>

        <el-radio-group v-model="loopCharacteristics" @change="changeLoopCharacteristicsType">
          <el-radio label="Null">非会签</el-radio>
          <el-radio label="ParallelMultiInstance">会签</el-radio>
          <el-radio label="SequentialMultiInstance">串签</el-radio>
        </el-radio-group>
      </el-form-item>

      <template
          v-if="loopCharacteristics === 'ParallelMultiInstance' || loopCharacteristics === 'SequentialMultiInstance'">
        <el-divider>辅助配置</el-divider>
        <el-form-item key="completeStrategy">
          <template slot="label">
            <el-tooltip effect="dark" placement="top">
              <i class="el-icon-question"/>
              <template slot="content">
                全部通过：多人审批时，所有审批人【审批】通过，流程即往下流转<br/>
                一票否决：多人审批时，只要有一个审批人【审批】不通过，流程即往下流转<br/>
                按比例通过：多人审批时，只要审批人【审批】通过率达到配置的比例，流程即往下流转<br/>
                或签（不适用串签）：多人审批时，任意一个审批人【审批】，流程即往下流转<br/>
              </template>
            </el-tooltip>
            <span> 完成策略</span>
          </template>
          <el-radio-group v-model="loopInstanceForm.completeStrategy" @change="changeCompletionConditionType">
            <el-radio label="1">全部通过</el-radio>
            <el-radio label="2">按通过比例</el-radio>
            <el-radio label="3">一票否决</el-radio>
            <el-radio label="4">一票通过</el-radio>
            <el-radio label="5" v-if="loopCharacteristics !== 'SequentialMultiInstance'">或签</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item key="completeRate" v-if="loopInstanceForm.completeStrategy === '2'">
          <template slot="label">
            <el-tooltip effect="dark" content="多人审批时，只要审批人【审批】通过率达到配置的比例，流程即往下流转" placement="top">
              <i class="el-icon-question"/>
            </el-tooltip>
            <span> 通过比例</span>
          </template>
          <el-row :gutter="10">
            <el-col :span="10">
              <el-slider v-model="loopInstanceForm.completeRate" @change="changeCompleteRate"></el-slider>
            </el-col>
            <el-col :span="12">
              <el-input-number v-model="loopInstanceForm.completeRate" @change="changeCompleteRate" :min="0" :max="100"></el-input-number>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item key="circulationStrategy">
          <template slot="label">
            <el-tooltip effect="dark" placement="top">
              <i class="el-icon-question"/>
              <template slot="content">
                流转任务：会签完成后，流程默认往下流转。可使用流程变量，使用网关条件判断进行流转。<br/><br/>
                通过（流程即往下流转），未通过（回退到上环节）<br/>
                通过（回退到上环节），未通过（流程即往下流转）<br/>
              </template>
            </el-tooltip>
            <span> 流转策略</span>
          </template>
          <el-radio-group v-model="loopInstanceForm.circulationStrategy" @change="changeCirculationStrategyType">
            <el-radio label="1">流转任务</el-radio>
            <el-radio label="2">通过（流转任务），未通过（回退任务）</el-radio>
            <el-radio label="3">通过（回退任务），未通过（流转任务）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-divider>自定义</el-divider>
        <el-form-item label="循环基数" key="loopCardinality">
          <el-input v-model="loopInstanceForm.loopCardinality" clearable @change="updateLoopCardinality"/>
        </el-form-item>
        <el-form-item label="集合" key="collection">
          <el-input v-model="loopInstanceForm.collection" clearable @change="updateLoopBase"/>
        </el-form-item>
        <el-form-item label="元素变量" key="elementVariable">
          <el-input v-model="loopInstanceForm.elementVariable" clearable @change="updateLoopBase"/>
        </el-form-item>
        <el-form-item label="完成条件" key="completionCondition">
          <el-input v-model="loopInstanceForm.completionCondition" clearable @change="updateLoopCondition"/>
        </el-form-item>
        <el-form-item label="异步状态" key="async">
          <el-checkbox v-model="loopInstanceForm.asyncBefore" label="异步前" @change="updateLoopAsync('asyncBefore')"/>
          <el-checkbox v-model="loopInstanceForm.asyncAfter" label="异步后" @change="updateLoopAsync('asyncAfter')"/>
          <el-checkbox
              v-model="loopInstanceForm.exclusive"
              v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
              label="排除"
              @change="updateLoopAsync('exclusive')"
          />
        </el-form-item>
        <el-form-item label="重试周期" prop="timeCycle"
                      v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore" key="timeCycle">
          <el-input v-model="loopInstanceForm.timeCycle" clearable @change="updateLoopTimeCycle"/>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "ElementMultiInstance",
  props: {
    businessObject: Object,
    type: String
  },
  inject: {
    prefix: "prefix"
  },
  data() {
    return {
      loopCharacteristics: "",
      //默认配置，用来覆盖原始不存在的选项，避免报错
      defaultLoopInstanceForm: {
        completionCondition: "",
        loopCardinality: "",
        asyncAfter: false,
        asyncBefore: false,
        exclusive: false
      },
      loopInstanceForm: {},
      extensionElements: []
    };
  },
  watch: {
    businessObject: {
      immediate: true,
      handler(val) {
        this.bpmnElement = window.bpmnInstances.bpmnElement;
        this.init(val);
      }
    }
  },
  methods: {
    init(businessObject) {
      if (!businessObject.loopCharacteristics) {
        this.loopCharacteristics = "Null";
        this.loopInstanceForm = {};
        return;
      }
      // 扩展元素
      this.extensionElements = this.bpmnElement.businessObject.loopCharacteristics.extensionElements || window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {values: []});
      //
      if (businessObject.loopCharacteristics.$type === "bpmn:StandardLoopCharacteristics") {
        this.loopCharacteristics = "StandardLoop";
        this.loopInstanceForm = {};
        return;
      }
      if (businessObject.loopCharacteristics.isSequential) {
        this.loopCharacteristics = "SequentialMultiInstance";
      } else {
        this.loopCharacteristics = "ParallelMultiInstance";
      }

      let extensionElement = {};
      if (this.extensionElements.values) {
        // 重试周期
        let failedJobRetryTimeCycle = this.extensionElements.values.find(element => element.$type === `${this.prefix}:FailedJobRetryTimeCycle`);
        if (failedJobRetryTimeCycle) {
          extensionElement.timeCycle = failedJobRetryTimeCycle.body;
        }
      }

      businessObject.loopCharacteristics.completeRate = parseInt(businessObject.loopCharacteristics.completeRate);
      // 合并配置
      this.loopInstanceForm = {
        ...this.defaultLoopInstanceForm,
        ...businessObject.loopCharacteristics,
        ...extensionElement,
        completionCondition: businessObject.loopCharacteristics?.completionCondition?.body ?? "",
        loopCardinality: businessObject.loopCharacteristics?.loopCardinality?.body ?? ""
      };

      // 保留当前元素 businessObject 上的 loopCharacteristics 实例
      this.multiLoopInstance = window.bpmnInstances.bpmnElement.businessObject.loopCharacteristics;
    },
    // 快捷配置
    changeCompletionConditionType(type) {
      //设置任务分配人从变量获取
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {assignee: '${assignee}'});

      //多实例配置
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        collection: '${multiInstanceHandler.getUserIds(execution)}',
        elementVariable: 'assignee',
        completeStrategy: type
      });

      //全部通过
      if (type === '1') {
        this.loopInstanceForm.completeRate = 100;
        this.updateLoopCondition('${multiInstanceHandler.completionCondition(execution)}');
      }
      //按通过比例
      else if (type === '2') {
        this.loopInstanceForm.completeRate = this.loopInstanceForm.completeRate || 100;
        this.updateLoopCondition('${multiInstanceHandler.completionCondition(execution)}');
      }
      //一票否决
      else if (type === '3') {
        this.loopInstanceForm.completeRate = null;
        this.updateLoopCondition('${multiInstanceHandler.completionCondition(execution)}');
      }
      //一票否决
      else if (type === '4') {
        this.loopInstanceForm.completeRate = null;
        this.updateLoopCondition('${multiInstanceHandler.completionCondition(execution)}');
      }
      // 或签
      else if (type === '5') {
        this.loopInstanceForm.completeRate = null;
        this.updateLoopCondition('${multiInstanceHandler.completionCondition(execution)}');
      }
      this.changeCompleteRate();
    },
    changeCompleteRate() {
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        completeRate: this.loopInstanceForm.completeRate
      });
    },
    changeCirculationStrategyType() {
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        circulationStrategy: this.loopInstanceForm.circulationStrategy
      });
    },
    // 会签类型变化
    changeLoopCharacteristicsType(type) {
      this.loopInstanceForm = { ...this.defaultLoopInstanceForm }; // 切换类型取消原表单配置
      // 取消多实例配置
      if (type === "Null") {
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {loopCharacteristics: undefined});
        return;
      }
      // 配置循环
      if (type === "StandardLoop") {
        const loopCharacteristicsObject = window.bpmnInstances.moddle.create("bpmn:StandardLoopCharacteristics");
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
          loopCharacteristics: loopCharacteristicsObject
        });
        this.multiLoopInstance = null;
        return;
      }
      // 时序
      if (type === "SequentialMultiInstance") {
        this.multiLoopInstance = window.bpmnInstances.moddle.create("bpmn:MultiInstanceLoopCharacteristics", {
          isSequential: true
        });
      } else {
        this.multiLoopInstance = window.bpmnInstances.moddle.create("bpmn:MultiInstanceLoopCharacteristics");
      }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        loopCharacteristics: this.multiLoopInstance
      });
    },
    // 循环基数
    updateLoopCardinality(cardinality) {
      let loopCardinality = null;
      if (cardinality && cardinality.length) {
        loopCardinality = window.bpmnInstances.moddle.create("bpmn:FormalExpression", {body: cardinality});
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        loopCardinality
      });
    },
    // 完成条件
    updateLoopCondition(condition) {
      let completionCondition = null;
      if (condition && condition.length) {
        completionCondition = window.bpmnInstances.moddle.create("bpmn:FormalExpression", {body: condition});
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        completionCondition
      });
    },
    // 重试周期
    updateLoopTimeCycle(timeCycle) {
      this.removeLoopTimeCycle();
      let failedJobRetryTimeCycle = window.bpmnInstances.moddle.create(`${this.prefix}:FailedJobRetryTimeCycle`, {body: timeCycle})
      this.extensionElements.values.push(failedJobRetryTimeCycle);
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        extensionElements: this.extensionElements
      });
    },
    removeLoopTimeCycle() {
      let elements = this.extensionElements.values;
      let length = elements.length;
      while (length--) {
        if (elements[length].$type === `${this.prefix}:FailedJobRetryTimeCycle`) {
          elements.splice(length, 1);
        }
      }
    },
    // 直接更新的基础信息
    updateLoopBase() {
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        collection: this.loopInstanceForm.collection || null,
        elementVariable: this.loopInstanceForm.elementVariable || null
      });
    },
    // 各异步状态
    updateLoopAsync(key) {
      const {asyncBefore, asyncAfter} = this.loopInstanceForm;
      let asyncAttr = Object.create(null);
      if (!asyncBefore && !asyncAfter) {
        this.$set(this.loopInstanceForm, "exclusive", false);
        this.removeLoopTimeCycle();
        asyncAttr = {asyncBefore: false, asyncAfter: false, exclusive: false, extensionElements: this.extensionElements};
      } else {
        asyncAttr[key] = this.loopInstanceForm[key];
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, asyncAttr);
    }
  },
  beforeDestroy() {
    this.multiLoopInstance = null;
    this.bpmnElement = null;
  }
};
</script>
